<template>
  <div class="bg-[#f5f5f5] p-4 pt-0">
    <!-- 顶部信息栏 -->
    <div
      v-if="isVisible && remainingAttempts > 0"
      class="flex justify-between text-[#666] text-sm mb-6 px-2 py-3 sticky top-0 bg-[#f7f8fa] z-10"
    >
      <div>
        剩余机会:
        <span class="text-lg font-semibold text-[#ff6b35]">
          {{ remainingAttempts }}
        </span>
      </div>
      <div>
        剩余时间:
        <span class="text-lg font-semibold text-[#00a3ff]">
          {{ formatTime(remainingTime) }}
        </span>
      </div>
    </div>

    <!-- 题目列表 -->
    <div class="space-y-4 mb-16 pt-2">
      <div
        v-for="(question, index) in questions"
        :key="index"
        class="bg-white rounded-lg shadow-[0_2px_8px_rgba(0,0,0,0.1)]"
      >
        <div
          v-if="loading"
          class="absolute inset-0 bg-white/80 flex items-center justify-center"
        >
          <div
            class="animate-spin h-8 w-8 border-4 border-[#00a3ff] rounded-full border-t-transparent"
          />
        </div>

        <!-- 题目标题 -->
        <h2
          class="text-lg font-semibold p-4 border-b border-[#eee] text-[#00a3ff]"
        >
          题目{{ index + 1 }}：{{ question.title }}
        </h2>

        <!-- 选项列表 -->
        <div class="p-4 space-y-3">
          <div
            v-for="option in question.options"
            :key="option.id"
            class="flex items-center p-3 rounded-lg border-2"
            :class="[
              selectedOptions[index] === option.option
                ? 'border-[#242424] bg-[#e6f7ff]'
                : 'border-[#00a3ff]/30 hover:border-[#00a3ff]/50'
            ]"
            @click="selectOption(index, option.option)"
          >
            <div class="relative w-5 h-5 mr-3">
              <div
                class="absolute inset-0 rounded-full border-2 border-[#00a3ff]"
                :class="{
                  'bg-[#00a3ff]': selectedOptions[index] === option.option
                }"
              >
                <div
                  v-if="selectedOptions[index] === option.option"
                  class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-2 h-2 bg-white rounded-full"
                />
              </div>
            </div>
            <div class="flex-1">
              <span class="text-[#00a3ff] font-bold mr-2">{{
                option.option
              }}</span>
              <span class="text-[#333]">{{ option.content }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <button
      v-if="isVisible && remainingAttempts > 0"
      class="mx-4 mt-4 mb-2 w-[calc(100%-32px)] h-12 bg-[#00a3ff] rounded-lg text-white text-base font-medium disabled:bg-[#ccc] disabled:cursor-not-allowed transition-all active:scale-[0.98] fixed bottom-0 left-0"
      :disabled="!isAllSelected"
      @click="handleConfirm"
    >
      确认
    </button>
  </div>
</template>

<script setup>
import { ref, onUnmounted, computed, watch, onMounted, watchEffect } from "vue";
import { showSuccessToast, showFailToast, showToast } from "vant";
import { useQuestionnaireStore } from "@/store/useQuestionnaireStore";

const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false
  },
  questions: {
    type: Array,
    default: () => []
  },
  answerTimeLimit: {
    type: Number,
    default: 30
  }
  // answerNum: {
  //   type: Number,
  //   default: 0
  // },
  // answerCount: {
  //   type: Number,
  //   default: 0
  // }
  // isAnswer: {
  //   type: Number,
  //   default: 0
  // }
});

const emit = defineEmits(["complete", "fail", "close", "timeout"]);

const questionnaireStore = useQuestionnaireStore();

// 倒计时相关
const remainingTime = ref(props.answerTimeLimit);
let countdownTimer = null;

const startCountdown = () => {
  countdownTimer = setInterval(() => {
    remainingTime.value--;
    if (remainingTime.value <= 0) {
      clearInterval(countdownTimer);
      handleTimeout();
    }
  }, 1000);
};

const handleTimeout = () => {
  showFailToast("答题时间结束！");
  emit("timeout");
  emit("close");
  clear();
};

const formatTime = seconds => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
};

const selectedOptions = ref([]);

const remainingAttempts = computed(() => {
  return Math.max(
    0,
    questionnaireStore.totalAttempts - questionnaireStore.usedAttempts
  );
});
console.log("remainingAttempts.value", remainingAttempts.value);

const loading = ref(false);

const selectOption = (questionIndex, value) => {
  selectedOptions.value[questionIndex] = value;
};

const isAllSelected = computed(() => {
  return props.questions.every(
    (_, index) => selectedOptions.value[index] !== undefined
  );
});

const handleConfirm = async () => {
  if (!isAllSelected.value || !props.isVisible) return;

  loading.value = true;
  await new Promise(resolve => setTimeout(resolve, 500));

  let allCorrect = true;
  props.questions.forEach((question, index) => {
    if (selectedOptions.value[index] !== question.successOption) {
      allCorrect = false;
    }
  });

  // 先调用答题次数记录接口
  await questionnaireStore.recordAnswerAttempt();

  if (allCorrect) {
    showSuccessToast("恭喜你完成所有题目！");
    emit("complete");
    clear();
    setTimeout(() => {
      emit("close");
    }, 500);
  } else {
    // 检查是否还有剩余次数，基于最新的数据进行判断
    if (remainingAttempts.value <= 0) {
      showFailToast(
        `当前题目答错${questionnaireStore.totalAttempts}次，答题结束！`
      );
      emit("fail");
      emit("close");
      clear();
    } else {
      showFailToast({
        message: `回答错误！剩余尝试次数：${remainingAttempts.value}`,
        duration: 1000,
        onClose: () => {
          selectedOptions.value = [];
        }
      });
    }
  }

  loading.value = false;
};

if (props.isVisible) {
  startCountdown();
  showToast("答题开始了！");
}
watch(
  () => props.isVisible,
  (newVal, oldVal) => {
    if (newVal) {
      startCountdown();
      showToast("答题开始了！");
    }
  }
);
const clear = () => {
  countdownTimer && clearInterval(countdownTimer);
};

onUnmounted(() => {
  clear();
});
</script>

<style>
/* 保持原有样式不变 */
button:active:not(:disabled) {
  transform: scale(0.98);
  box-shadow: 0 2px 4px rgba(0, 163, 255, 0.2);
}

div[class*="hover:border"] {
  transition:
    border-color 0.2s ease,
    background-color 0.2s ease,
    transform 0.1s ease;
}
</style>
